<template>
  <div>
    <!-- 搜索结果页-头部导航 -->
    <div class="search-result-container">
      <!-- 点击实现后退效果 -->
      <van-nav-bar
        title="搜索结果"
        left-arrow
        @click-left="$router.go(-1)"
        fixed
      />
    </div>
    <div>
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :isShow="false"
      >
        <ArticleItem
          v-for="obj in searchResultList"
          :key="obj.art_id"
          :articleItem="obj"
          :isShow="false"
          @click.native="articleClickFn(obj.art_id)"
        ></ArticleItem>
      </van-list>
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import * as relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'

import { searchResultAPI } from '@/api'
import ArticleItem from '@/components/ArticleItem'
// 插件
dayjs.locale('zh-cn') // use locale
dayjs.extend(relativeTime)
export default {
  name: 'SearchResult',
  data () {
    return {
      title: '',
      page: 1,
      searchResultList: [], // 用于获取搜索界面的文章
      loading: false,
      finished: false
    }
  },
  components: {
    ArticleItem
  },
  methods: {
    onLoad () {
      this.page++
      this.getSearchResultFn()
    },
    async getSearchResultFn () {
      const res = await searchResultAPI({
        page: this.page,
        q: this.$route.params.keyWords
        // 拿到关键词, keywords来源于router/index.js你定义的动态路由参数名
      })
      if (
        res.data.data.results === null ||
        res.data.data.results.length === 0
      ) {
        this.finished = true // 加载完成
      }
      console.log(res)
      this.searchResultList = [
        ...this.searchResultList,
        ...res.data.data.results
      ]
      this.loading = false
    },
    // 点击跳转到文章详情
    articleClickFn (art_id) {
      this.$router.push({
        path: '/article_detail',
        query: {
          aid: art_id
        }
      })
    }
  },

  created () {
    this.getSearchResultFn()
  }
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
</style>
